import { stringGbLength } from '@vimi/utils-tool'

/**
 * 截取字符串，中文字符占两个长度
 * @param {String} str 要截取的原始字符串
 * @param {Int} len 截取长度
 * @param {Boolean} dot 是否在后面加“...”
 */
export const gbSubstr = (str, len, dot = false) => {
  // eslint-disable-next-line
  const chineseReg = new RegExp(/[^\x00-\xff]/, 'g')
  const strLen = stringGbLength(str)
  let res = ''
  if (strLen > len) {
    let singleChar = ''
    let newLen = 0
    let endStr = ''
    if (dot) {
      --len
      endStr = '...'
    }
    for (let i = 0; i < len; i++) {
      singleChar = str.charAt(i)
      newLen += singleChar && singleChar.match(chineseReg) ? 2 : 1
      if (newLen > len) {
        break
      }
      res += singleChar || ''
    }
    res += endStr
  } else {
    res = str
  }
  return res
}
